package co.msk8.client.visual.calculator.view;

import co.msk8.shared.OperationContainer;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;

public class CalculatorViewWidget extends Composite implements CalculatorView<OperationContainer> {

	private static CalculatorViewWidgetUiBinder uiBinder = GWT
			.create(CalculatorViewWidgetUiBinder.class);

	interface CalculatorViewWidgetUiBinder extends
			UiBinder<Widget, CalculatorViewWidget> {
	}
	
	//==== UiBinder fields ====//
	@UiField TextArea taValues;
	
	@UiField Button bBackSpace;
	@UiField Button bUndo;
	@UiField Button bClear;
	
	@UiField Button button0;
	@UiField Button button1;
	@UiField Button button2;
	@UiField Button button3;
	@UiField Button button4;
	@UiField Button button5;
	@UiField Button button6;
	@UiField Button button7;
	@UiField Button button8;
	@UiField Button button9;
	
	
	@UiField Button buttonAdd;
	@UiField Button buttonSub;
	@UiField Button buttonMul;
	@UiField Button buttonDiv;
	@UiField Button buttonEq;
	
	
	//==== Class fields ====//
	private CalculatorPresenter<OperationContainer> presenter;

	
	/**
	 * Constructor.
	 */
	public CalculatorViewWidget() {
		
		initWidget(uiBinder.createAndBindUi(this));
	}
	
	//==== EVENTS ====//
	@UiHandler(value = { "button0", "button1", "button2", "button3", "button4",
			"button5", "button6", "button7", "button8", "button9"})
	public void onClickNumericPad(ClickEvent evt) {
		
		HasText clicked = (Button) evt.getSource();
		addDigit(clicked.getText());
	}
	
	@UiHandler(value = { "buttonAdd", "buttonSub", "buttonMul", "buttonDiv", "buttonEq"})
	public void onClickNumericOperator(ClickEvent evt) {
		
		HasText clicked = (Button) evt.getSource();
		addOperator(clicked.getText());
	}
	
	//==== ADDITIONAL METHODS ====//

	public HasValue<String> getDisplay() {
		
		return taValues;
	}


	public void setPresenter(CalculatorPresenter<OperationContainer> calculatorPresenterImpl) {

		this.presenter = calculatorPresenterImpl;
	}

	public void addDigit(String digit) {
		presenter.addDigit(digit);
	}
	
	private void addOperator(String symbol) {
		
		presenter.addOperator(symbol);
	}


	public void setOperationText(String operationText) {
		taValues.setText(operationText);
	}

}
